package cn.hpclub.server.session;


import java.io.Serializable;
import java.util.*;

import com.jfinal.plugin.redis.Redis;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.util.CollectionUtils;


/**
 * 只负责redis的增删改查，用于集群，不要cache，不能继承于enterprisecache
 */
public class RedisSessionDao extends AbstractSessionDAO {
//    private int  sessionExpireTime   = SystemConfigUtil.getSystemConfig().getSessionExpireTime()*60;
      private int  redisSessionAliveTime   = 1800;//redis session alive time.redis session记录存活时间。默认30分钟,单位为秒

    // 创建session，保存到redis
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        this.storeSession(sessionId, session);
//        System.out.println("doCreate,sessionId:"+sessionId+",timeout:"+session.getTimeout());
        return sessionId;

    }

    /**
     * @param sessionId
     * @return
     */
    // 从redis获取session
    @Override
    protected Session doReadSession(Serializable sessionId) {

        Session session= Redis.use().get(sessionId);
//        System.out.println("doReadSession,sessionId:"+sessionId);
//        if(session!=null){
//            System.out.println("doReadSession,getLastAccessTime:"+session.getLastAccessTime());
//        }
//        System.out.println("read "+session);
        return session;
    }


    /**
     * @param session
     * @throws UnknownSessionException
     * 更新redis
     */
    public void update(Session session) throws UnknownSessionException {
//         System.out.println("doUpdate,sessionId:"+session.getId()+",start time:"+session.getStartTimestamp());
//         System.out.println("last acess time:"+session.getLastAccessTime()+",timeout:"+session.getTimeout());
        this.storeSession(session.getId(), session);
    }


    public void delete(Session session) {
        if (session == null) {
            throw new NullPointerException("session argument cannot be null.");
        } else {
//            System.out.println("doDelete,sessionId:"+session.getId());
            Redis.use().del(session.getId());
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        // 获取所有key
        Set<String> keys =  Redis.use().keys("*");
        if((keys==null)||(keys.size()<=0)){
            return Collections.emptySet();
        }
        // 获取所有value
        List<Session> sessions = Redis.use().mget(keys.toArray());

        System.out.println("getActiveSessions:"+sessions.size());
        return (Collection)(CollectionUtils.isEmpty(sessions) ? Collections.emptySet() : Collections.unmodifiableCollection(sessions));
    }

    protected void storeSession(Serializable id, Session session) {
        if (id == null) {
            throw new NullPointerException("id argument cannot be null.");
        }else{
            Redis.use().setex(id,redisSessionAliveTime,session);
        }

    }

}